package com.jh.cloud.stream.client.controller;

import com.jh.cloud.stream.client.stream.SimpleMessageProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/stream")
public class MessageController {

    @Autowired
    private SimpleMessageProvider simpleMessageProvider;

    @GetMapping("/msg")
    public String getMessage(@RequestParam("message") String message) {
        // 获取 channel
        MessageChannel channel = simpleMessageProvider.output();

        // 构造消息
        Map<String, Object> headers = new HashMap<>(4);
        headers.put("charset-encoding", "UTF-8");
        headers.put("content-type", MediaType.TEXT_PLAIN_VALUE);
        GenericMessage<String> msg = new GenericMessage<>(message, headers);

        // 发送到mq
        channel.send(msg);

        return "OK";
    }

    @GetMapping("/send/rocketmq")
    public Boolean streamSendRocketMQ(@RequestParam("message") String message) {
        MessageChannel channel = simpleMessageProvider.testChannel();
        boolean flag = channel.send(new GenericMessage<>(message));
        return flag;
    }

}
